<template>
    <div class="app-container">
        <el-form ref="queryRef" :model="queryParams" :inline="true" v-show="showSearch" label-width="68px"
                 scroll-to-error>
            <el-form-item label="关键字" prop="keyword">
                <el-input v-model="queryParams.keyword" placeholder="请输入描述" clearable
                          style="width: 130px" @keyup.enter="handleQuery"/>
            </el-form-item>
            <el-form-item v-if="managedDeptOptions.length>1" label="监所名称" prop="deptId">
                <el-select v-model="queryParams.deptId" placeholder="请选择监所" filterable clearable
                           style="width: 130px">
                    <el-option v-for="dept in managedDeptOptions" :label="dept.deptName" :value="dept.deptId"/>
                </el-select>
            </el-form-item>
            <el-form-item label="责任科室（监区）" prop="subDept" class="long-form-item">
                <el-select v-model="queryParams.subDept" placeholder="请选择责任科室（监区）" filterable clearable
                           allow-create default-first-option style="width: 130px;">
                    <el-option v-for="dict in sub_dept" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="隐患等级" prop="level">
                <el-select v-model="queryParams.level" placeholder="请选择等级" clearable style="width: 130px">
                    <el-option v-for="dict in hazard_level" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="隐患类型" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择类型" clearable style="width: 130px">
                    <el-option v-for="dict in hazard_type" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="督办等级" prop="superviseLevel">
                <el-select v-model="queryParams.superviseLevel" placeholder="请选择督办等级" clearable
                           style="width: 130px">
                    <el-option v-for="dict in supervise_level" :key="dict.value" :label="dict.label"
                               :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="整改状态" prop="finished">
                <el-select v-model="queryParams.finished" placeholder="请选择状态" clearable style="width: 130px">
                    <el-option v-for="dict in finishOptions" :key="dict.value" :label="dict.label" :value="dict.value"/>
                </el-select>
            </el-form-item>
            <el-form-item label="检查时间" style="width: 274px">
                <el-date-picker v-model="dateRangeCheck" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                                start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="整改期限" style="width: 274px">
                <el-date-picker v-model="dateRangeDeadline" value-format="YYYY-MM-DD" type="daterange"
                                range-separator="-"
                                start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item label="整改完成" style="width: 274px">
                <el-date-picker v-model="dateRangeFinish" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
                                start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
            <el-form-item v-if="alarmRecord.id">
                <el-tag size="large" type="primary" round closable hit @close="handleAlarmRecordClear">
                    {{ alarmRecord.tag }}
                </el-tag>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd"
                           v-hasPermi="['hazard:add']">新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                           v-hasPermi="['hazard:update']">修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
                           v-hasPermi="['hazard:delete']">删除
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['hazard:import']">
                    导入
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['hazard:export']">
                    导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="hazardList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50" align="center"/>
            <el-table-column v-for="col in columns.filter(c=>c.visible)" v-bind="col">
                <template v-if="col.slotName=='sub'" #default="{row}">
                    <dict-tag :options="sub_dept" :value="row.subDept"/>
                </template>
                <template v-if="col.slotName=='type'" #default="{row}">
                    <dict-tag :options="hazard_type" :value="row.type"/>
                </template>
                <template v-if="col.slotName=='level'" #default="{row}">
                    <dict-tag :options="hazard_level" :value="row.level"/>
                </template>
                <template v-if="col.slotName=='deadline'" #default="{row}">
                    <el-text :type="row.delayed?'danger':''">{{ row.deadline }}</el-text>
                </template>
                <template v-if="col.slotName=='supervise'" #default="{row}">
                    <dict-tag :options="supervise_level" :value="row.superviseLevel"/>
                </template>
                <template v-if="col.slotName=='finish'" #default="{row}">
                    <el-text v-if="row.finished" type="success">已整改</el-text>
                    <el-tag v-else type="danger">未整改</el-tag>
                </template>
                <template v-if="col.slotName=='images'" #default="{row}">
                    <el-text type="primary" size="small" class="cursor-pointer" @click="handleImagePreview(row)">
                        <el-icon>
                            <View/>
                        </el-icon>
                        预览({{ row.images.length }})
                    </el-text>
                </template>
                <template v-if="col.slotName=='images2'" #default="{row}">
                    <el-text type="primary" size="small" class="cursor-pointer" @click="handleImage2Preview(row)">
                        <el-icon>
                            <View/>
                        </el-icon>
                        预览({{ row.images2.length }})
                    </el-text>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width"
                             fixed="right" v-if="editEnable||improveEnable||finishEnable">
                <template #default="scope">
                    <el-button v-if="finishEnable&&!scope.row.finished" link type="primary" size="small"
                               icon="CircleCheck" @click="handleFinish(scope.row)">销号
                    </el-button>
                    <el-button link type="primary" size="small" icon="Edit" @click="handleUpdate(scope.row)">修改
                    </el-button>
                    <el-button v-if="checkPermi(['hazard:delete'])" link type="primary" size="small" icon="Delete"
                               @click="handleDelete(scope.row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize" @pagination="getList"/>

        <!-- 添加或修改文件配置对话框 -->
        <el-dialog :title="title" v-model="open" width="920px" append-to-body>
            <el-form :model="form" :rules="rules" ref="hazardRef" label-width="80px">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="监所名称" prop="deptId">
                            <el-select v-model="form.deptId" :disabled="!editEnable" filterable
                                       placeholder="请选择监所">
                                <el-option v-for="dict in managedDeptOptions" :label="dict.deptName"
                                           :value="dict.deptId"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="责任科室（监区）" prop="subDept" class="long-form-item">
                            <el-select v-model="form.subDept" :disabled="!editEnable" filterable allow-create
                                       default-first-option placeholder="请选择责任科室（监区）">
                                <el-option v-for="dict in sub_dept" :label="dict.value" :value="dict.label"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="隐患等级" prop="level">
                            <el-select v-model="form.level" :disabled="!editEnable" placeholder="请选择隐患等级"
                                       @change="handleLevelChanged">
                                <el-option v-for="dict in hazard_level" :key="dict.value" :label="dict.label"
                                           :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="隐患类型" prop="type">
                            <el-select v-model="form.type" :disabled="!editEnable" placeholder="请选择隐患类型">
                                <el-option v-for="dict in hazard_type" :key="dict.value" :label="dict.label"
                                           :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="检查日期" prop="checkDate">
                            <el-date-picker v-model="form.checkDate" :disabled="!editEnable" value-format="YYYY-MM-DD"
                                            placeholder="请填写检查日期" @change="handleCheckDateChange"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="整改期限" prop="deadline">
                            <el-date-picker v-model="form.deadline" :disabled="!editEnable" value-format="YYYY-MM-DD"
                                            placeholder="请填写整改期限"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="督办" prop="superviseLevel">
                            <el-select v-model="form.superviseLevel" :disabled="!editEnable" clearable
                                       placeholder="请选择督办等级">
                                <el-option v-for="dict in supervise_level" :key="dict.value" :label="dict.label"
                                           :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="具体位置" prop="location">
                            <el-input v-model="form.location" :disabled="!editEnable" placeholder="请输入隐患具体位置"
                                      maxlength="100"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="隐患描述" prop="description">
                            <el-input v-model="form.description" :disabled="!editEnable" type="textarea"
                                      placeholder="请输入隐患描述" maxlength="500"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="整改前图片" prop="attachmentsImage" class="long-form-item">
                                    <image-upload v-model="form.attachmentsImage" :disabled="!editEnable" :limit="10"
                                                  :data="uploadType"></image-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row v-if="false">
                            <el-col :span="24">
                                <el-form-item label="隐患文件" prop="attachmentsDocument">
                                    <file-upload v-model="form.attachmentsDocument" :disabled="!editEnable" :limit="10"
                                                 :data="uploadType"></file-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="12">
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="整改后图片" prop="attachmentsImage2" class="long-form-item">
                                    <image-upload v-model="form.attachmentsImage2" :disabled="!improveEnable"
                                                  :limit="10"
                                                  :data="uploadType"></image-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="其它附件" prop="attachmentsDocument2">
                                    <file-upload v-model="form.attachmentsDocument2" :disabled="!improveEnable"
                                                 :limit="10"
                                                 :data="uploadType"></file-upload>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="整改说明" prop="remark">
                            <el-input v-model="form.remark" :disabled="!improveEnable" type="textarea"
                                      placeholder="请输入整改说明" maxlength="500"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="finishEnable">
                    <el-col :span="6">
                        <el-form-item label="整改完成" prop="finishDate">
                            <el-date-picker v-model="form.finishDate" value-format="YYYY-MM-DD"
                                            placeholder="请填写完成日期"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="整改状态" prop="finished">
                            <el-select v-model="form.finished" placeholder="请选择整改状态" clearable>
                                <el-option v-for="dict in finishOptions" :key="dict.value" :label="dict.label"
                                           :value="dict.value"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 完成整改 -->
        <el-dialog title="整改完成" v-model="finishOpen" width="400px" append-to-body>
            <el-form :model="finishForm" :rules="finishRules" ref="finishRef" label-width="120px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="整改完成日期" prop="finishDate">
                            <el-date-picker v-model="finishForm.finishDate" value-format="YYYY-MM-DD"
                                            placeholder="请填写整改完成日期"/>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="handleFinishConfirm">确 定</el-button>
                    <el-button @click="finishOpen=false">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 文件导入对话框 -->
        <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
            <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                       :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
                       :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false"
                       drag>
                <el-icon class="el-icon--upload">
                    <upload-filled/>
                </el-icon>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <template #tip>
                    <div class="el-upload__tip text-center">
                        <div class="el-upload__tip">
                            <el-checkbox v-model="upload.updateSupport"/>
                            如果更新数据请勾选此项
                        </div>
                        <span>仅允许导入xls、xlsx格式文件。</span>
                        <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                                 @click="importTemplate">下载模板
                        </el-link>
                    </div>
                </template>
            </el-upload>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFileForm">确 定</el-button>
                    <el-button @click="upload.open = false">取 消</el-button>
                </div>
            </template>
        </el-dialog>

        <!--   图片预览    -->
        <el-image-viewer v-if="showImagePreview" :url-list="previewImages"
                         @close="showImagePreview=false"></el-image-viewer>
    </div>
</template>

<script setup name="Hazard">
import {getToken} from "@/utils/auth"
import {appendDateRange, consts} from "@/utils/hazard.js";
import {
    listHazard,
    addHazard,
    updateHazard,
    delHazard,
    finishHazard,
    setHazardAlarmRead
} from "@/api/business/hazard.js";
import {useManagedDept} from "@/hooks/useManagedDept.js";
import FileUpload from "@/components/FileUpload/index.vue";
import ImageUpload from "@/components/ImageUpload/index.vue";
import {UploadFilled} from "@element-plus/icons-vue";
import DictTag from "@/components/DictTag/index.vue";
import {useRoute} from "vue-router";
import {addDays, formatDate} from "@/utils/index.js";
import {checkPermi} from "@/utils/permission.js";

const route = useRoute()
const baseUrl = import.meta.env.VITE_APP_BASE_API
const {proxy} = getCurrentInstance()
const {
    hazard_type,
    hazard_level,
    sub_dept,
    supervise_level
} = proxy.useDict("hazard_type", "hazard_level", "sub_dept", "supervise_level")

const {managedDeptOptions} = useManagedDept()
const hazardList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dateRangeCheck = ref([])
const dateRangeDeadline = ref([])
const dateRangeFinish = ref([])
const uploadType = {type: consts.enum.uploadType.hazard}
const showImagePreview = ref(false)
const previewImages = ref('')
const alarmRecord = ref({id: undefined, tag: undefined})

const editEnable = computed(() => checkPermi(['hazard:update', 'hazard:add']))
const improveEnable = computed(() => checkPermi(['hazard:improve']))
const finishEnable = computed(() => checkPermi(['hazard:finish']))

/*** 文件导入参数 */
const upload = reactive({
    // 是否显示弹出层（文件导入）
    open: false,
    // 弹出层标题（文件导入）
    title: "",
    // 是否禁用上传
    isUploading: false,
    // 是否更新已经存在的文件数据
    updateSupport: 0,
    // 设置上传的请求头部
    headers: {Authorization: "Bearer " + getToken()},
    // 上传的地址
    url: import.meta.env.VITE_APP_BASE_API + "/hazard/importData"
})
// 列显隐信息
const columns = ref([
    {key: -1, label: `序号`, visible: true, prop: 'id', width: 70},
    {key: 0, label: `监所名称`, visible: true, prop: 'deptName', width: 80},
    {key: 1, label: `责任科室（监区）`, visible: true, prop: 'subDept', width: 100, slotName: 'sub'},
    {key: 2, label: `具体位置`, visible: true, prop: 'location', showOverflowTooltip: true},
    {key: 3, label: `隐患描述`, visible: true, prop: 'description', minWidth: 150, showOverflowTooltip: true},
    {key: 4, label: `隐患等级`, visible: true, prop: 'level', width: 100, slotName: 'level'},
    {key: 5, label: `隐患类型`, visible: true, prop: 'type', width: 100, slotName: 'type'},
    {key: 6, label: `检查时间`, visible: true, prop: 'checkDate', width: 100},
    {key: 7, label: `整改期限`, visible: true, prop: 'deadline', width: 100, slotName: 'deadline'},
    {key: 8, label: `整改完成日期`, visible: false, prop: 'finishDate', width: 120},
    {key: 9, label: `整改前附件`, visible: false, prop: 'attachmentsImage', slotName: 'images', width: 90},
    {key: 10, label: `整改后附件`, visible: false, prop: 'attachmentsImage2', slotName: 'images2', width: 90},
    {key: 11, label: `整改说明`, visible: false, prop: 'remark', showOverflowTooltip: true, minWidth: 150},
    {key: 12, label: `督办`, visible: true, prop: 'superviseLevel', slotName: 'supervise', fixed: 'right', width: 80},
    {key: 13, label: `整改状态`, visible: true, prop: 'finished', slotName: 'finish', fixed: 'right', width: 80}
])

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        deptId: undefined,
        subDept: undefined,
        keyword: undefined,
        type: undefined,
        level: undefined,
        superviseLevel: undefined,
        finished: undefined
    },
    rules: {
        deptId: [{required: true, message: "请选择监所", trigger: "blur"}],
        subDept: [{required: true, message: "请选择责任科室（监区）", trigger: "blur"}],
        level: [{required: true, message: "请选择隐患等级", trigger: "blur"}],
        type: [{required: true, message: "请选择隐患类型", trigger: "blur"}],
        checkDate: [{required: true, message: "请填写检查时间", trigger: "blur"}],
        deadline: [{required: true, message: "请填写整改期限", trigger: "blur"}],
        location: [{required: true, message: "请填写具体位置", trigger: "blur"}, {
            max: 100,
            message: "具体位置长度必须小于 100",
            trigger: "blur"
        }],
        description: [{required: true, message: "请填写隐患描述", trigger: "blur"}, {
            max: 500,
            message: "描述长度必须小于 500",
            trigger: "blur"
        }],
        remark: [{max: 500, message: "整改说明长度必须小于 500", trigger: "blur"}]
    },
    // 操作确认弹窗
    finishOpen: false,
    finishForm: {id: undefined, finishDate: undefined},
    finishRules: {
        finishDate: [{required: true, message: '请选择整改完成日期'}]
    }
})

const finishOptions = ref([
    {label: '未整改', value: false},
    {label: '已整改', value: true}
])

const {
    queryParams, form, rules,
    finishOpen, finishForm, finishRules
} = toRefs(data)

function mergeParams() {
    // merge into a new object.
    let query = {...queryParams.value} // make a copy
    query = appendDateRange(query, dateRangeCheck.value, 'checkDate')
    query = appendDateRange(query, dateRangeDeadline.value, 'deadline')
    query = appendDateRange(query, dateRangeFinish.value, 'finishDate')
    if (alarmRecord.value.id) query.alarmRecordId = alarmRecord.value.id
    return query
}

/** 查询隐患列表 */
function getList() {
    loading.value = true
    listHazard(mergeParams()).then(res => {
        const today = formatDate(new Date(), true)
        res.rows.forEach(h => {
            // default value assignment for safety
            h.documents = h.attachmentsDocument?.split(',') || []
            h.images = h.attachmentsImage?.split(',') || []
            h.documents2 = h.attachmentsDocument2?.split(',') || []
            h.images2 = h.attachmentsImage2?.split(',') || []
            // delayed - local calculation
            h.delayed = !h.finished && h.deadline && h.deadline < today
        })
        loading.value = false
        hazardList.value = res.rows
        total.value = res.total
    })
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1
    getList()
}

/** 重置按钮操作 */
function resetQuery() {
    dateRangeCheck.value = []
    dateRangeDeadline.value = []
    dateRangeFinish.value = []
    proxy.resetForm("queryRef")
    handleQuery()
}

/** 删除按钮操作 */
function handleDelete(row) {
    const idList = row.id || ids.value
    proxy.$modal.confirm('是否确认删除隐患序号为"' + idList + '"的数据项？').then(function () {
        return delHazard(idList)
    }).then(() => {
        getList()
        proxy.$modal.msgSuccess("删除成功")
    }).catch(() => {
    })
}

/** 导出按钮操作 */
function handleExport() {
    proxy.download("hazard/export", mergeParams(), `隐患导出_${new Date().getTime()}.xlsx`)
}

/** 选择条数  */
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.id)
    single.value = selection.length != 1
    multiple.value = !selection.length
}

/** 导入按钮操作 */
function handleImport() {
    upload.title = "文件导入"
    upload.open = true
}

/** 下载模板操作 */
function importTemplate() {
    proxy.download("hazard/importTemplate", {}, `隐患导入模板_${new Date().getTime()}.xlsx`)
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
    upload.isUploading = true
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
    upload.open = false
    upload.isUploading = false
    proxy.$refs["uploadRef"].handleRemove(file)
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true})
    getList()
}

/** 提交上传文件 */
function submitFileForm() {
    proxy.$refs["uploadRef"].submit()
}

/** 重置操作表单 */
function reset() {
    form.value = {
        id: undefined,
        name: undefined,
        deptId: undefined,
        subDept: undefined,
        type: undefined,
        level: undefined,
        location: undefined,
        checkDate: undefined,
        deadline: undefined,
        finishDate: undefined,
        remark: undefined,
        superviseLevel: undefined,
        attachmentsDocument: undefined,
        attachmentsImage: undefined,
        attachmentsDocument2: undefined,
        attachmentsImage2: undefined,
        finished: undefined
    }
    proxy.resetForm("hazardRef")
}

/** 取消按钮 */
function cancel() {
    open.value = false
    reset()
}

/** 新增按钮操作 */
function handleAdd() {
    reset()
    open.value = true
    title.value = "添加隐患"
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset()
    const id = row.id || ids.value
    const hazard = hazardList.value.find(h => h.id == id)
    form.value = {...hazard} // make a copy
    open.value = true
    title.value = "修改隐患"
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["hazardRef"].validate((valid, errors) => {
        if (valid) {
            if (form.value.id != undefined) {
                updateHazard(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功")
                    open.value = false
                    getList()
                })
            } else {
                addHazard(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功")
                    open.value = false
                    getList()
                })
            }
        } else if (errors) {
            // {location: [{message: '', field: ''}]}
            const demoField = Object.values(errors)[0]
            if (demoField) {
                const demoError = demoField[0]
                if (demoError.message) return proxy.$modal.msgError(demoError.message)
            }
        }
    })
}

function handleLevelChanged() {
    trySetDefaultSuperviseLevel()
    trySetDefaultDeadline()
}

function handleCheckDateChange() {
    trySetDefaultDeadline()
}

function trySetDefaultDeadline() {
    if (form.value.checkDate && form.value.level && !form.value.deadline) {
        const daysConfig = {'一般（蓝）': 5, '一般（黄）': 30, '重大': 90}
        const days = daysConfig[form.value.level]
        if (days) form.value.deadline = addDays(form.value.checkDate, days)
    }
}

function trySetDefaultSuperviseLevel() {
    if (form.value.level == '重大' && !form.value.superviseLevel) {
        form.value.superviseLevel = '省局督办' // 重大隐患强制督办，默认督办等级
    }
}

function handleImagePreview(row) {
    if (!row.images.length) return proxy.$modal.msg('没有图片附件可供预览')
    previewImages.value = row.images.map(url => baseUrl + url)
    showImagePreview.value = true
}

function handleImage2Preview(row) {
    if (!row.images2.length) return proxy.$modal.msg('没有图片附件可供预览')
    previewImages.value = row.images2.map(url => baseUrl + url)
    showImagePreview.value = true
}

function handleFinish(row) {
    finishForm.value.id = row.id
    finishForm.value.finishDate = row.finishDate || ''
    finishOpen.value = true
}

async function handleFinishConfirm() {
    await proxy.$refs.finishRef.validate()
    const {id, finishDate} = finishForm.value
    finishHazard(id, finishDate).then(res => {
        finishOpen.value = false
        proxy.$modal.msgSuccess("状态已更新")
        getList()
    })
}

function handleAlarmRecordClear() {
    alarmRecord.value = {id: undefined, tag: undefined}
    getList()
}

watch(() => route.query.alarm, val => {
    if (val) {
        alarmRecord.value = JSON.parse(decodeURIComponent(val))
        if (alarmRecord.value.id) {
            setHazardAlarmRead(alarmRecord.value.id)
            getList()
        }
    }
})
onBeforeMount(() => {
    if (!route.query?.data) return
    // JSON parse to keep params raw type
    const data = JSON.parse(decodeURIComponent(route.query.data))
    Object.keys(data).forEach(key => {
        queryParams.value[key] = data[key]
    })
})
onBeforeMount(() => {
    if (!route.query?.alarm) return
    alarmRecord.value = JSON.parse(decodeURIComponent(route.query.alarm))
    if (alarmRecord.value.id) setHazardAlarmRead(alarmRecord.value.id)
})
onMounted(() => {
    getList()
})
</script>

<style scoped lang="scss">
</style>